package devcken.springframework.security.web.authentication;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.util.CookieGenerator;

public class AuthenticationSuccessEventListener extends SavedRequestAwareAuthenticationSuccessHandler
{
	private static final String _SAVING_USER_NAME_COOKIE_NAME = "_SAVED_USER_NAME";
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException
	{
		if (authentication.getPrincipal() instanceof User)
		{
			User user = (User)authentication.getPrincipal();
			
			CookieGenerator cookie = new CookieGenerator();
			
			cookie.setCookieName(_SAVING_USER_NAME_COOKIE_NAME);
			
			if (ServletRequestUtils.getBooleanParameter(request, "savingUserName", false))
			{
				cookie.setCookieMaxAge(Integer.MAX_VALUE);
				cookie.addCookie(response, user.getUsername());
			}
			else
			{
				cookie.setCookieMaxAge(-1);
				cookie.removeCookie(response);
			}
		}
		
		super.onAuthenticationSuccess(request, response, authentication);
	}
}